import "../css/Usermange.css";
import zhCN from "antd/lib/locale/zh_CN";
import axios, { all } from "axios";
import "../mock/Usermanage/UsermanageData";
import "../mock/Usermanage/TreeData";
import { useState, useEffect } from "react";
import {
  Input,
  Button,
  Tree,
  Divider,
  Radio,
  Table,
  Dropdown,
  ConfigProvider,
  Space,
  Modal,
  Form,
  Select,
  Row,
  Col,
  Tag,
  Checkbox,
  TreeSelect,
  message,
  Popconfirm,
} from "antd";

import {
  PlusSquareOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
  MoreOutlined,
  UserAddOutlined,
  FormOutlined,
  MinusCircleOutlined,
  KeyOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
const { Option } = Select;
const { TreeNode } = TreeSelect;

const UserManage = () => {
  // const [allTabledata, setAllTabledata] = useState({});
  const { TreeNode } = Tree;
  const [tree_data, setdata] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [currentName, setcurrentName] = useState("我是palceholder默认值");
  const [inputValue, setinputValue] = useState("我是input默认值");
  const [newName, setnewName] = useState("我是新增默认值");
  //暂存当前table(临时表)
  let cursor = [];
  const tableColumns = [
    {
      title: "用户名",
      dataIndex: "userName",
    },
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "组织机构",
      dataIndex: "organization",
    },
    {
      title: "职务",
      dataIndex: "job",
    },
    {
      title: "用户类型",
      dataIndex: "customerType",
    },
    {
      title: "联系方式",
      dataIndex: "contact",
    },
    {
      title: "有效期",
      dataIndex: "effectiveTime",
    },
    {
      title: "创建来源",
      dataIndex: "createSource",
    },
    {
      title: "状态",
      dataIndex: "status",
    },
    {
      title: "操作",
      dataIndex: "operate",
      render: (text, record, index) => (
        <Space size="middle">
          <FormOutlined>Invite </FormOutlined>
          <KeyOutlined />
          <Popconfirm
            title="禁用"
            description="您确定要禁用他吗?"
            onConfirm={confirm(record, index)}
            onCancel={cancel}
            okText="是"
            cancelText="取消"
          >
            <MinusCircleOutlined>Delete</MinusCircleOutlined>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const confirm = (record, index) => {
    if (record.status == "正常") {
      record.status = "已禁用";
      // console.log(record, index);
      // cursor = record;
      // setTableData(cursor);
    } else {
      record.status = "正常";
      // console.log(record, index);
    }
    // message.success("Click on Yes");
  };
  const cancel = (e) => {
    console.log(e);
    message.error("Click on No");
  };
  //添加用户弹出框
  const { Option } = Select;
  const layout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 60,
    },
  };
  const tailLayout = {
    wrapperCol: {
      offset: 20,
      span: 30,
    },
  };
  const [form] = Form.useForm();
  const onGenderChange = (value) => {
    switch (value) {
      case "longtime":
        form.setFieldsValue({
          note: "Hi, man!",
        });
        break;
      case "time":
        form.setFieldsValue({
          note: "Hi, lady!",
        });
        break;
      case "other":
        form.setFieldsValue({
          note: "Hi there!",
        });
        break;
      default:
    }
  };
  const onFinish = (values) => {
    console.log(values);
  };
  const onReset = () => {
    form.resetFields();
  };
  const onFill = () => {
    form.setFieldsValue({
      note: "Hello world!",
      gender: "male",
    });
  };
  function checkboxonChange(e) {
    console.log(`checked = ${e.target.checked}`);
  }
  const [table_tree1, settable_tree1] = useState();
  const Change_table_tree1 = (newValue) => {
    settable_tree1(newValue);
  };
  const columns = [
    {
      title: "组织机构",
      dataIndex: "name",
      key: "name",
      render: (text) => (
        <TreeSelect
          showSearch
          style={{
            width: "100%",
          }}
          value={table_tree1}
          dropdownStyle={{
            maxHeight: 400,
            overflow: "auto",
          }}
          placeholder="Please select"
          allowClear
          treeDefaultExpandAll
          onChange={Change_table_tree1}
          treeData={initTreedata}
        />
      ),
    },
    {
      title: "职务",
      dataIndex: "age",
      key: "age",
    },

    {
      title: "是否设为默认组织",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <Space size="middle">
          <Checkbox onChange={checkboxonChange}></Checkbox>
        </Space>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <DeleteOutlined onClick={() => {}} />
        </Space>
      ),
    },
  ];
  const data = [
    {
      key: new Date(),
      name: undefined,
      age: undefined,
      address: undefined,
      tags: undefined,
    },
  ];
  //end
  const [isModalOpenAdduser, setIsModalOpenAdduser] = useState(false);
  const showModalAdduser = () => {
    setIsModalOpenAdduser(true);
  };
  const handleOkAdduser = () => {
    setIsModalOpenAdduser(false);
  };
  const handleCancelAdduser = () => {
    setIsModalOpenAdduser(false);
  };

  //end
  const [initTreedata, setinitTreedata] = useState([]);
  useEffect(() => {
    axios.get("/treedata", { dataType: "json" }).then((res) => {
      //初始化数据
      setTableData(res.data.data.treeData[0].data);

      setinitTreedata(res.data.data.treeData);

      setdata(res.data.data.treeData);

      console.log(res.data.data.treeData);
    });
  }, []);

  //编辑
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOkmodify = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const changeName = (e) => {
    // console.log("currentName", currentName);
    // let input = e.target.value;
    // console.log(input);
    setIsModalOpen(false);
  };
  const changeName1 = (e) => {
    setinputValue(e.target.value);
  };
  // const editName = (item) => {
  //   console.log(item);
  //   const promise = new Promise((resolve, reject) => {
  //     isModalOpen === true ? resolve() : reject();
  //   })
  //     .then(() => {
  //       console.log("res");
  //     })
  //     .catch(() => {
  //       item.value = inputValue;
  //       console.log("修改");
  //     });

  //   return item;
  // };
  const [isModalOpenadd, setIsModalOpenadd] = useState(false);
  const showModaladd = () => {
    setIsModalOpenadd(true);
  };
  const handleOkadd = () => {
    setIsModalOpenadd(false);
  };
  const handleCanceladd = () => {
    setIsModalOpenadd(false);
  };
  const addName = () => {
    setIsModalOpenadd(false);
  };
  const addName1 = (e) => {
    setnewName(e.target.value);
  };
  const renderTreeNodes = (tree_data) => {
    const Dropdownfn = (props) => {
      const { itemid } = props;
      const items = [
        {
          key: "1",
          label: <span onClick={showModaladd}>新增</span>,
        },
        {
          key: "2",
          label: <span onClick={showModal}>修改</span>,
        },
        {
          key: "3",
          label: (
            <>
              <span
                onClick={() => {
                  console.log(itemid);
                  let alldata = tree_data;
                  // console.log(alldata);
                  alldata.map((item, index, arr) => {
                    if (itemid === "1" || itemid === "2" || itemid === "3") {
                      arr.splice(itemid - 1, 1);
                    }
                    // if (itemid.length != 1 && itemid.substr(0, 1) == 1) {
                    //   console.log(arr);
                    //   console.log(alldata);
                    // } else if (itemid.length != 1 && itemid.substr(0, 1) == 2) {
                    //   console.log(alldata[1]);
                    // } else if (itemid.length != 1 && itemid.substr(0, 1) == 3) {
                    //   console.log(alldata[2]);
                    // }
                    // setdata(alldata);
                  });
                }}
              >
                删除
              </span>
            </>
          ),
        },
      ];
      return (
        <>
          <Dropdown
            menu={{
              items,
            }}
            placement="bottom"
            arrow={{
              pointAtCenter: true,
            }}
            onClick={edit}
          >
            <MoreOutlined
              style={{
                marginLeft: 100,
                position: "absolute",
                right: 0,
                top: 5,
              }}
              onClick={edit}
            ></MoreOutlined>
          </Dropdown>
        </>
      );
    };
    const edit = () => {
      console.log("编辑");
    };
    let nodeArr = tree_data.map((item) => {
      item.title = (
        <div
          style={{ width: 200, position: "relative" }}
          onClick={() => {
            setTableData(item.data);
            cursor = item.data;
            console.log(item.data);
            setcurrentName(item.value);
            // const itemName1 = editName(item);
            // promise.then((res) => {
            //   item.value = inputValue;
            // });

            // console.log(item.id);
            // console.log(item.value);

            // item.value = itemname;
          }}
        >
          <span>{item.value}</span>
          <Dropdownfn itemid={item.id} />
        </div>
      );

      if (item.children) {
        // console.log(item);
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }

      return <TreeNode title={item.title} key={item.key} />;
    });

    return nodeArr;
  };

  const SearchInput = () => (
    <Input
      placeholder="请输入用户名和姓名"
      style={{ width: 200, marginLeft: 20 }}
    />
  );
  const Searchbtn = () => (
    <Button type="primary" style={{ marginLeft: 20 }}>
      搜索
    </Button>
  );
  const Resetbtn = () => <Button style={{ marginLeft: 20 }}>重置</Button>;

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
    },
  };
  const UserTable = () => {
    return (
      <div>
        <ConfigProvider locale={zhCN}>
          <Table
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            columns={tableColumns}
            dataSource={tableData}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              // size: "small",
              // total: 12,
              // position: ["bottomCenter"],
              // showQuickJumper: true,
            }}
          />
        </ConfigProvider>
      </div>
    );
  };

  //新增用户

  return (
    <div className="Box">
      <div className="flexTitle">
        <div className="title1">
          <span>数据组织</span>
          <PlusSquareOutlined onClick={showModaladd} />
          <CloudDownloadOutlined />
          <CloudUploadOutlined />
        </div>
        <div className="tree">
          <Tree>{renderTreeNodes(tree_data)}</Tree>
        </div>
      </div>
      <div className="flexContent">
        <div className="title2">
          <span>全部用户</span>
        </div>
        <div className="userlist">
          <div className="userlist_title">
            <span>
              <UserAddOutlined />
              <span onClick={showModalAdduser} style={{ cursor: "pointer" }}>
                添加用户
              </span>
              <Modal
                title="添加用户"
                open={isModalOpenAdduser}
                onOk={handleOkAdduser}
                onCancel={handleCancelAdduser}
                width={940}
                footer={null}
                destroyOnClose={true}
              >
                <Form
                  {...layout}
                  form={form}
                  name="control-hooks"
                  onFinish={onFinish}
                  style={{
                    maxWidth: 940,
                  }}
                >
                  <Row gutter={64}>
                    <Col span={32}>
                      <Form.Item
                        name="username"
                        label="用户名"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: true,
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                    </Col>
                    <Col span={32}>
                      <Form.Item
                        name="name"
                        label="姓名"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: true,
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={64}>
                    <Col span={32}>
                      <Form.Item
                        name="contact"
                        label="联系方式"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: false,
                          },
                        ]}
                      >
                        <Input />
                      </Form.Item>
                    </Col>
                    <Col span={32}>
                      <Form.Item
                        name="customer type"
                        label="用户类型"
                        style={{ width: 400 }}
                        rules={[
                          {
                            required: false,
                          },
                        ]}
                      >
                        <Select
                          placeholder="普通用户"
                          onChange={onGenderChange}
                          allowClear
                          placement={"bottomLeft"}
                        >
                          <Option value="user">普通用户</Option>
                          <Option value="manager">管理员</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={63}>
                    <Col span={63}>
                      <Form.Item
                        name="term of validity"
                        label="有效期"
                        rules={[
                          {
                            required: true,
                          },
                        ]}
                      >
                        <Select
                          placeholder="长期"
                          onChange={onGenderChange}
                          allowClear
                          style={{ width: 200 }}
                        >
                          <Option value="longtime">长期</Option>
                          <Option value="time">期间</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  <span>
                    注意:新创建用户的默认密码为
                    <span style={{ color: "red" }}>"Szl@2023!"</span>
                    ，请及时修改密码!
                  </span>
                  <div
                    style={{ marginLeft: 48, marginTop: 20, marginBottom: 30 }}
                  >
                    <Button type="primary">添加组织机构和工作职务</Button>
                  </div>
                  <div>
                    <Table columns={columns} dataSource={data} />
                  </div>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.gender !== currentValues.gender
                    }
                  >
                    {({ getFieldValue }) =>
                      getFieldValue("gender") === "other" ? (
                        <Form.Item
                          name="customizeGender"
                          label="Customize Gender"
                          rules={[
                            {
                              required: true,
                            },
                          ]}
                        >
                          <Input />
                        </Form.Item>
                      ) : null
                    }
                  </Form.Item>

                  <Form.Item {...tailLayout}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      onClick={handleCancelAdduser}
                    >
                      提交
                    </Button>
                    <Button htmlType="button" onClick={handleCancelAdduser}>
                      关闭
                    </Button>
                  </Form.Item>
                </Form>
              </Modal>
            </span>
            <span style={{ cursor: "pointer" }}>
              <UserAddOutlined />
              下载用户
            </span>
            <span style={{ cursor: "pointer" }}>
              <UserAddOutlined />
              上传用户
            </span>
            <span style={{ cursor: "pointer" }}>
              用户名或姓名:
              <SearchInput />
              <Searchbtn />
              <Resetbtn />
            </span>
          </div>
          <div className="userlist_content">
            <UserTable />
          </div>
        </div>
      </div>
      <Modal
        title="修改"
        open={isModalOpen}
        onOk={handleOkmodify}
        onCancel={handleCancel}
        destroyOnClose={true}
        style={{ paddingTop: 30 }}
      >
        <span style={{ marginLeft: 50 }}>名称：</span>
        <Input
          placeholder={currentName}
          style={{ width: 350 }}
          onPressEnter={changeName}
          onChange={changeName1}
        />
      </Modal>
      <Modal
        title="新增"
        open={isModalOpenadd}
        onOk={handleOkadd}
        onCancel={handleCanceladd}
        destroyOnClose={true}
        style={{ paddingTop: 30 }}
      >
        <span style={{ marginLeft: 50 }}>名称：</span>
        <Input
          placeholder={""}
          style={{ width: 350 }}
          onPressEnter={addName}
          onChange={addName1}
        />
      </Modal>
    </div>
  );
};

export default UserManage;
